const types = require('../action-types.js');
const {request} = require('utils/request');
function switchImgRepo(visible) {
  return {
    type: types.SWITCH_IMG_REPO,
    imgRepoVisible: visible
  };
}

function setImgTags(tags) {
  return {
    type: types.SET_IMG_TAGS,
    tags
  };
}

function queryImgTags() {
  return async (dispatch, getState) => {
    const res = await request({
      url: 'api/source/list/img_tag',
      method: 'post',
      data: {
        columns: ['id', 'name'],
        pageSize: 100
      }
    });
    if (res.code === '0') {
      dispatch({
        type: types.SET_IMG_TAGS,
        tags: res.data.list
      });
    }
  };
}

function addImgTags(name) {
  return async (dispatch, getState) => {
    const res = await request({
      url: 'api/source/add/img_tag',
      method: 'post',
      data: {
        data: {
          name
        }
      }
    });
    if (res.code === '0') {
      dispatch(queryImgTags());
    }
    return res;
  };
}

function queryImgsByTag(tagId = '-1', pageNum = 1) {
  return async (dispatch) => {
    const filters = [];
    if (tagId && tagId !== 'all') {
      filters.push({
        column: 'tagId',
        filterKey: 'equal',
        value: tagId
      });
    }
    const res = await request({
      url: 'api/source/list/img_repo',
      method: 'post',
      data: {
        columns: ['id', 'url'],
        filters,
        pageSize: 8,
        pageNum
      }
    });
    if (res.code === '0') {
      dispatch({
        type: types.SET_REPO_IMGS,
        data: res.data
      });
    }
  };
}

function addImgs({tagId = '-1', url}) {
  return async (dispatch) => {
    const res = await request({
      url: 'api/source/add/img_repo',
      method: 'post',
      data: {
        data: {
          tagId: tagId === 'all' ? '-1' : tagId,
          url
        }
      }
    });
    if (res.code === '0') {
      await dispatch(queryImgsByTag(tagId, 1));
      dispatch(setImgRepoPage(1));
      return res;
    }
  };
}

function setImgRepoPage(page) {
  return {
    type: types.SET_IMG_PAGE,
    page
  };
}

function setCurrTag(tag) {
  return {
    type: types.SET_CURR_TAG,
    tag
  };
}

module.exports = {
  switchImgRepo,
  setImgTags,
  queryImgTags,
  addImgTags,
  queryImgsByTag,
  addImgs,
  setImgRepoPage,
  setCurrTag
};
